package com.ybc.chinese.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ybc.chinese.R;
import com.ybc.chinese.adapter.HomeAdapter;
import com.ybc.chinese.bean.CarouselFigure;
import com.ybc.chinese.bean.Home;
import com.ybc.chinese.utils.CacheUtil;
import com.ybc.chinese.utils.CommonUtil;
import com.ybc.chinese.utils.Contants;
import com.ybc.chinese.widget.autoScroll.AutoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * <p>首页<p/>
 * Created by Yubch on 17/2/18.
 */
public class HomeFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView> {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.lv_home)
    PullToRefreshListView lvHome;
    public static final String INDEX_CAROUSE_FIGURE = "index/carousel/figure";
    public static final String INDEX_HOME = "index/home";
    private Context mCtx;
    private HomeAdapter mAdapter;
    private int mOffset = 0;

    public static HomeFragment newInstance() {
        HomeFragment homeFragment = new HomeFragment();
        return homeFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mCtx = getActivity();
        View view = inflater.from(mCtx).inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        initView();
        List<CarouselFigure> carouselFigures = getCacheCarouseFigure();
        if (!CommonUtil.isEmpty(carouselFigures)) {
            mAdapter.setCaroueslFigures(carouselFigures);
        }
        List<Home> homes = getCacheHome();
        if (!CommonUtil.isEmpty(homes)) {
            mAdapter.setData(homes, false);
        } else {
            showRunningDialog();
        }
        requestCarouselFigure();
        requestHome();
        return view;
    }

    private void initView() {
        tvTitle.setText(getString(R.string.home));
        mAdapter = new HomeAdapter(mCtx);
        lvHome.setAdapter(mAdapter);
        lvHome.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
        lvHome.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        lvHome.setOnRefreshListener(this);
    }

    /**
     * 请求轮播图
     */
    private void requestCarouselFigure() {
        if (!CommonUtil.isNetworkConnected(mCtx)) {
            dismissRunningDialog();
            CommonUtil.showToast(mCtx, R.string.no_net);
            lvHome.onRefreshComplete();
            return;
        }
        BmobQuery<CarouselFigure> query = new BmobQuery<>();
        //按照时间降序
        query.order("-createdAt");
        //执行查询，第一个参数为上下文，第二个参数为查找的回调
        query.findObjects(new FindListener<CarouselFigure>() {

            @Override
            public void done(List<CarouselFigure> list, BmobException e) {
                if (e == null) {
                    CacheUtil.saveCache(mCtx, INDEX_CAROUSE_FIGURE, new Gson().toJson(list));
                    mAdapter.setCaroueslFigures(list);
                } else {
                    CommonUtil.showToast(mCtx, "数据请求失败");
                }
            }
        });
    }

    private List<CarouselFigure> getCacheCarouseFigure() {
        String jsonCarouselFigure = CacheUtil.getCache(mCtx, INDEX_CAROUSE_FIGURE);
        List<CarouselFigure> carouselFigures = new ArrayList<>();
        if (!TextUtils.isEmpty(jsonCarouselFigure)) {
            carouselFigures = new Gson().fromJson(jsonCarouselFigure, new TypeToken<List<CarouselFigure>>() {
            }.getType());
        }
        return carouselFigures;
    }

    private List<Home> getCacheHome() {
        String jsonHome = CacheUtil.getCache(mCtx, INDEX_HOME);
        List<Home> homes = new ArrayList<>();
        if (!TextUtils.isEmpty(jsonHome)) {
            homes = new Gson().fromJson(jsonHome, new TypeToken<List<Home>>() {
            }.getType());
        }
        return homes;
    }

    /**
     * 请求列表
     */
    private void requestHome() {
        if (!CommonUtil.isNetworkConnected(mCtx)) {
            dismissRunningDialog();
            CommonUtil.showToast(mCtx, R.string.no_net);
            lvHome.onRefreshComplete();
            return;
        }
        BmobQuery<Home> query = new BmobQuery<>();
        query.setLimit(Contants.LIMIT);
        query.setSkip(mOffset);
        //按照时间降序
        query.order("-createdAt");
        //执行查询，第一个参数为上下文，第二个参数为查找的回调
        query.findObjects(new FindListener<Home>() {

            @Override
            public void done(List<Home> list, BmobException e) {
                if (e == null) {
                    try {
                        if(mOffset == 0) {
                            mAdapter.setData(list, false);
                            CacheUtil.saveCache(mCtx, INDEX_HOME, new Gson().toJson(list));
                        } else {
                            mAdapter.setData(list, true);
                        }
                        mOffset = mOffset + list.size();
                    } catch (Exception ignore) {
                    }
                } else {
                    CommonUtil.showToast(mCtx, "数据请求失败");
                }
                dismissRunningDialog();
                lvHome.onRefreshComplete();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            if (mAdapter != null && mAdapter.getHomeTopView() != null && mAdapter.getHomeTopView().getVpCarousel() != null) {
                AutoScrollViewPager autoScrollViewPager = mAdapter.getHomeTopView().getVpCarousel();
                autoScrollViewPager.startAutoScroll();
            }
        } catch (Exception ignore) {
            ignore.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        try {
            if (mAdapter != null && mAdapter.getHomeTopView() != null && mAdapter.getHomeTopView().getVpCarousel() != null) {
                AutoScrollViewPager autoScrollViewPager = mAdapter.getHomeTopView().getVpCarousel();
                autoScrollViewPager.stopAutoScroll();
            }
        } catch (Exception ignore) {
            ignore.printStackTrace();
        }
        super.onPause();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mOffset = 0;
        requestCarouselFigure();
        requestHome();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        requestHome();
    }
}
